﻿/*
 * common.h
 *
 *  Created on: 2020年5月3日
 *      Author: root
 */

#ifndef SRC_COMMON_H_
#define SRC_COMMON_H_
//---------------------------------------------------------------------------

#include <pthread.h>
#include <sys/time.h>
#include "datatype.h"
//---------------------------------------------------------------------------

class TLock
{
private:
    bool FInit;
    pthread_mutex_t mutex;
public:
    TLock();
    ~TLock();

    bool GetInit();
    void Lock();
    void Unlock();
};
//---------------------------------------------------------------------------

class TAutoMem
{
private:
    BYTE *pData;
    uint32 dwSize;
public:
    TAutoMem(uint32 uSize);
    ~TAutoMem();

	void ReSize(uint32 uSize);		//按指定大小重新分配内存
	void Free();					//释放空间
	void ZeroFill();				//0填充缓冲区

	inline BYTE * GetBuffer() { return pData; }
	inline uint32 GetSize() { return dwSize; }
};
//---------------------------------------------------------------------------

class TTimerEx
{
private:
	L_TIME FTime0;
	UINT32 FMilliseconds;

	UINT32 L_TIME2Seconds(L_TIME ATime);
	UINT32 L_TIME2Milliseconds(L_TIME ATime);
public:
	TTimerEx();

	L_TIME Now();						//取当前时间值
	UINT32 NowSeconds();				//取当前时间值(秒数)
	UINT32 NowMilliseconds();			//取当前时间值(毫秒数)

	void Begin();						//开始计时
	UINT32 Elapsed();					//从开始计时到现在经过的时间(毫秒数)
};
//---------------------------------------------------------------------------

extern bool IsExit;

extern bool FileExists(char *pzfile);
extern void Trim(char * &pzChar);
extern uint16 CalcCRC16(BYTE *pBuff, int iSize);
extern void ntoipv4(uint32 n, char *pOut);
extern uint32 ipv4ton(const char *pzIp);
extern bool IsIPv4(const char *pzIp);

extern void ByteToAsc2(BYTE bt, BYTE asc[2]);
extern BYTE Asc2ToByte(BYTE asc[2]);
extern uint16 Asc4ToWord(BYTE asc[4]);
extern uint32 Asc8ToUint32(BYTE asc[8]);
extern BYTE ByteToCBCD(BYTE bt);
extern BYTE CBCDToByte(BYTE bt);
extern uint16 WordToCBCD(uint16 w);
extern uint16 CBCDToWord(uint16 w);
extern void U32ToCBCD(uint32 uVal, BYTE *pBuffer, BYTE len);
extern uint32 CBCDToU32(BYTE *pBuffer, BYTE len);

extern TTIMEX GetDateTime();
extern void SleepEx(int ms, bool *pWorking = NULL);

extern bool DecodeFrame(TFRAMEBIN *pfrm, BYTE *pBuffer, int iSize);
extern bool EncodeFrame(TFRAMEBIN *pfrm, BYTE *pBuffer, int &iSize);
extern void CalcFrameCRC(TFRAMEBIN *pfrm);
//---------------------------------------------------------------------------

#endif /* SRC_COMMON_H_ */
